<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Exception;
class ActivityController extends Controller {
	// 创新活动列表
	public function showlist(){
		$activity=D('activity');
		$list=$activity->select();
		// dump($list);die;
		$arr=array();
		foreach ($list as $k => $v) {
				$startdate=$v['startdate'];
				$enddate=$v['enddate'];
				$bmdate=$v['bmdate'];
				$now=time();
				if($now<strtotime($bmdate)){
					$v['status']='0';
				}
			 	if(strtotime($startdate)>$now && $now>strtotime($bmdate)){
					$v['status']='1';
				}
				if($now>strtotime($startdate)||$v['restticket']=="0"){
					$v['status']='2';
				}
			$arr[$k]=$v;
		}
		$this->assign('list',$arr);
		$this->display ();
	}
	
	// 发布活动
	public function add() {
		$activity=D('activity');
		if (IS_POST) {
				// $data=I('post.')
				$data['aname']=$_POST['aname'];
				$data['startdate']=$_POST['startdate'];
				$data['enddate']=$_POST['enddate'];
				$data['totalticket']=$_POST['totalticket'];
				$data['place']=$_POST['place'];
				$data['desc']=$_POST['desc'];
				$data['content']=$_POST['content'];
				$data['bmdate']=$_POST['bmdate'];
				if ($activity->create()) {
					if($activity->add($data)){
	    				$this->success('添加成功！',U('showlist'));
	    			}else{
	    				$this->error('添加失败！');
	    			}
	    		}
	    		else{
	    			$this->error($activity->getError());
	    		}
			return;
		}
		$this->display ();
	}
	// 修改活动
	public function edit($aid){
		$activity=D('activity');
		if (IS_POST) {
				$data['aid']=$_POST['aid'];
				$data['aname']=$_POST['aname'];
				$data['startdate']=$_POST['startdate'];
				$data['enddate']=$_POST['enddate'];
				$data['bmdate']=$_POST['bmdate'];
				$data['totalticket']=$_POST['totalticket'];
				$data['place']=$_POST['place'];
				$data['desc']=$_POST['desc'];
				$data['content']=$_POST['content'];
				// dump($data);
			if ($activity->create()) {
				if($activity->save($data)!==false){
    				$this->success('添加成功！',U('showlist'));
    			}else{
    				$this->error('添加失败！');
    			}
			}else{
				$this->error($activity->getError());
			}
			return;
		}
		$act=$activity->find($aid);
		$this->assign('act',$act);
		$this->display ();
	}


		public function detial($aid) {
		$activity=D('activity');
		$stu_activity=D('stu_activity');
		$res=$activity->find($aid);
		$stu=$stu_activity->field('a.id,a.state,a.score,b.realname,b.stunum')->alias('a')->join('users b ON a.uid=b.uid')->where(array('aid'=>$aid))->order('id desc')->select();
		// echo $stu_activity->getLastSql();
		$this->assign('list',$res);
		$this->assign('stu',$stu);
		$this->display ();
	}
	
	// 删除活动
	public function del($aid){
		$stu_activity=D('stu_activity');
		$res=$stu_activity->where(array('aid'=>$aid))->select();
		try {
			// $this->isStudent($aid);
			if($res){
			throw new Exception("此活动有报名学生");
				}
			}
		catch (Exception $e) {
			print $e->getMessage();
			}
			// $result=$this->isStudent($aid);
		if ($res){
				$this->error('删除失败');
			}else{
					$activity=D('activity');
					$res=$activity->delete($aid);
					if ($res) {
						$this->success('删除成功',U('showlist'));
					}else{
					$this->error('删除失败');
					}	
			}	
	}
		public function	stuedit(){
		$data=$_GET;
		$stu_activity=D('stu_activity');
		$res=$stu_activity->save($data);
		if ($res) {
			echo "1";
		}else{
			echo "0";
		}
	}
	// 导入学生名单
public function instu(){
 		$aid=I('aid');
 		if (IS_POST) {
 			header("Content-Type:text/html;charset=utf-8");
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('xls', 'xlsx');// 设置附件上传类
        $upload->savePath  =      'Public/UPLOADS/excelData/'; // 设置附件上传目录
        $upload->rootPath  =      './'; 
        // 上传文件
        $info   =   $upload->uploadOne($_FILES['excelData']);
        $filename =$info['savepath'].$info['savename'];
        $exts = $info['ext'];
        if(!$info) {// 上传错误提示错误信息
              $this->error($upload->getError());
          }else{// 上传成功
          			// dump('1');die;
          	$data['aid']=I('aid');
          	$data['excelData']=$filename;
          	$data['exts']=$exts;
          	$this->goods_import($filename, $exts);
        	}
		// dump($data);die();
        	return;
 		}
        $this->assign('aid',$aid);
	    $this->display();
}
 //导入数据方法
    protected function goods_import($filename, $exts='xls')
    {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import("Org.Util.PHPExcel");
        //创建PHPExcel对象，注意，不能少了\
        $PHPExcel=new \PHPExcel();
        //如果excel文件后缀名为.xls，导入这个类
        if($exts == 'xls'){
            import("Org.Util.PHPExcel.Reader.Excel5");
            $PHPReader=new \PHPExcel_Reader_Excel5();
        }else if($exts == 'xlsx'){
            import("Org.Util.PHPExcel.Reader.Excel2007");
            $PHPReader=new \PHPExcel_Reader_Excel2007();
        }


        //载入文件
        $PHPExcel=$PHPReader->load($filename);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet=$PHPExcel->getSheet(0);
        //获取总列数
        $allColumn=$currentSheet->getHighestColumn();
        //获取总行数
        $allRow=$currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        $arr=array();
        for($currentRow=2;$currentRow<$allRow;$currentRow++){
            //从哪列开始，A表示第一列
            $date=null;
            for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $cell =$currentSheet->getCell($address)->getValue();
                //$cell = $data[$currentRow][$currentColumn];
                if($cell instanceof PHPExcel_RichText){
                    $cell  = $cell->__toString();
                }
              
               $date[]=$cell;
            }
                
                $arr[$currentRow]=$date;
        } 
// dump($arr);die;
        $this->save_import($arr);
    }

    public function save_import($arr){
    		// dump($arr);die;
    		$stu_activity=D('stu_activity');
    		foreach ($arr as $k => $v) {
			$data = array('score'=>trim($v[3]),'state'=>$v[4]);
			$stu_activity->where(array('id'=>$v[0]))->setField($data);	
    			$data=null;
    		} 
    		$this->success('导入成功',U('showlist'));

    }
// 导出学生名单
	public function exstu($aid,$aname){

		$filename=$aname;
		$stu_activity=D('stu_activity');
		$stu=$stu_activity->field('a.id,a.state,a.score,b.realname,b.stunum')->alias('a')->join('users b ON a.uid=b.uid')->where(array('aid'=>$aid))->order('id asc')->select();
		$data=array();
		foreach ($stu as $k => $v) {
			$data[$k]['id']=$v['id'];
			$data[$k]['stunum']=$v['stunum'];
			$data[$k]['realname']=$v['realname'];
			$data[$k]['score']=$v['score'];
			$data[$k]['state']=$v['state'];
		}
		 $headArr[]='ID';
		 $headArr[]='学号';
		 $headArr[]='姓名';
		 $headArr[]='分数';
		 $headArr[]='出勤状态(已参加/缺席)';
 		$this->getExcel($filename,$headArr,$data);
	}

    private  function getExcel($fileName,$headArr,$data){
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");

        $fileName .= ".xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //设置表头
        $key = ord("A");
        //print_r($headArr);exit;
        foreach($headArr as $v){
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
            $key += 1;
        }

        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet();

        //print_r($data);exit;
        foreach($data as $key => $rows){ //行写入
            $span = ord("A");
            foreach($rows as $keyName=>$value){// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j.$column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);

        //重命名表
        //$objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }

    public function saveresult($aid){
    	$data['result']=$_GET['result'];
    	// $data['aid']=$aid;
    	// dump($data);
    	$data['startdate']=$_GET['startdate'];
    	$data['enddate']=$_GET['enddate'];
    	$data['bmdate']=$_GET['bmdate'];

		$activity=M('activity');
		$time=$activity->field('startdate,enddate,bmdate')->where(array('aid'=>$aid))->find($aid);
		$data['startdate']=$time['startdate'];
    	$data['enddate']=$time['enddate'];
    	$data['bmdate']=$time['bmdate'];

    	
		// dump($data);
		// dump($time);
		// die;
		$res=$activity->where(array('aid'=>$aid))->save($data);
		if ($res!==false) {
			echo "1";
		}else{
			echo "0";
		}

    }


}